import React, {useEffect, useRef, useState, useCallback} from "react";

import html2canvas from 'html2canvas'
import type {MenuProps} from 'antd';
import {Button, Col, Collapse, Form, message, Modal, Progress, Row, Select, Tag, Input, Tree, Space} from 'antd';
import JsPDF from "jspdf";
// import DevTreeList from "~/public/cpas-ui/components-ui/express-components/DevListTree";
import "./_index.less"
import {getAllData, getLeftTreeList, queryDataState, queryResetState, fetchReportList} from "../tab1/server";
import { CloseOutlined } from '@ant-design/icons';
import {formatPrice, getDataId} from "~/public/cpas-business/tools/Tools"
import {useModel} from "umi";
import Dexie from "dexie"
import {DoubleRightOutlined} from "@ant-design/icons";
import {nodeTreeList, sortCpasTable, sortValidtorData, ellipsis} from './utils'
import PageLoading from "@/pages/components/PageLoading";
import { resetPidIfNotFound } from '@/utils/index'
import _, { AnyKindOfDictionary } from "lodash";
import {getAllCpasTable} from "./service";
import type { DataNode } from 'antd/es/tree';
import TreeView from 'devextreme-react/tree-view';
import { TextBox } from 'devextreme-react/text-box';
const { Panel } = Collapse;
const { Search } = Input;
// const  OPTIONS = ['与报表校验', '表内交叉校验', '表内校验', '表间校验'];
const OPTIONS = [
  {
    label: "表内校验",
    value: "1"
  },
  {
    label: "表间校验",
    value: "2"
  },
  {
    label: "与报表校验",
    value: "3"
  },
  {
    label: "表内交叉校验",
    value: "4"
  },
]

const RESULT_OPATIONS = [
  {
    label: "校验不通过",
    value: "1"
  },
  {
    label: "强制校验不通过",
    value: "2"
  },
  {
    label: "非强制校验不通过",
    value: "3"
  },
  {
    label: "差异数项目",
    value: "4"
  },
  {
    label: "逻辑不符项目",
    value: "5"
  }
];

// import { dataList as dataListTree } from "./defaultData"

const TabPageTwo = ({ modileIsReturn, type, storageName, title, openVerifyDetail}: any) => {
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const { dbname } = initialState?.curPart as API.CurPart;
  const treeRef = useRef<any>(null)
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [isShowOpen, setShowOpen] = useState<boolean>(false)

  const [resultItems, setResultItems] = useState<string[]>([]);
  const [reportResult, setReportResult] = useState<string[]>([])
  const [reportItem, setReportItem] = useState<string[]>([])
  const [dataList, setDataList] = useState<any>([])
  const [totalData, setTotalData] = useState<any>({})
  const [otherData, setOtherData] = useState<any>({})
  const [activeKeyArr, setActiveKeyArr] = useState<any>([])
  const [percentNum, setPercentNum] = useState<any>(0)
  const [contentMsg, setContentMsg] = useState("")
  const [isLoading,setIsLoading] = useState<boolean>(false)
  const [isReportModalOpen, setReportModalOpen] = useState<boolean>(false)
  const [isNotesModalOpen, setNotesModalOpen] = useState<boolean>(false)
  const [reportDataSource, setReportDataSource] = useState<any>([])
  // const [getDataIds, setDataIds] = useState(null)
  const filteredReportOpation = reportResult.filter((o)=>!reportItem.includes(o))
  // const [otherCheck, setOtherCheck] = useState(false)
  const [reportChecks, setReportChecks] = useState<any>([])
  const [reportInputValue, setReportInputValue] = useState<any>([])
  const [notesChecks, setNotesChecks] = useState<any>([])
  const [notesInputValue, setNotesInputValue] = useState<any>([])
  // const [searchValue, setSearchValue] = useState("");
  const reportTreeView = useRef<any>();
  const notesTreeView = useRef<any>();
  const [isClickRerun, setIsClickRerun] = useState<boolean>(false)
  const RulesType ={
    "1": "表内校验",
    "2": "表间校验",
    "3": "与报表校验",
    "4": "交叉校验"
  }
  // 附注数据
  const getReportProject = async () => {
    try {
      const dateId = await getDataId()
      const res = await getLeftTreeList(dbname, dateId)
      if(res && res.length) {
        console.log(res,"披露项目数据");
        const data = resetPidIfNotFound(res);
        const dataTree = data.map((item: any) => {
          const obj = {
            icon: "icon-biaogeyangshiku",
            parentId: item.pid,
            // expanded: true,
            key: item.title,
            isDirectory: true,
            ...item
          }
          return obj
        })
        setReportResult(dataTree);
      }
    }catch(err) {
      console.log(err, '错误处理');
    }
  }
  // 获取报表项目
  const getReportList = async () => {
    const dateId = await getDataId()
    const params = {
      dbName: dbname,
      year: dateId
    }
    const reportList: any = await fetchReportList(params)
    if (!reportList.ok) {
      return message.error("暂无报表项目!!!")
    } else {
      const list = reportList.data.filter((item: any) => {
        item.key = item.itemName
        item.title = item.itemName
        item.id = item.code
        const children = reportList.data.filter((e: any) => {
          e.key = e.itemName
          e.title = e.itemName
          e.id = e.code
          return item.code === e.pCode
        })
        item.children = children;
        item.items = children;
        return !item.pCode
      })
      console.log(list, 'list---');
      return setReportDataSource(list)
    }
  }
  //报表数据
  const initFsTableData = async () => {
    const fsData = await getAllCpasTable({
      type: "fs",
      dbname,
    });
    if (fsData.success) {
      const newFsData = fsData.data.map((item: any) => {
        const obj = {
          ...item,
          value: item.tid,
          label: item.name,
          title: item.name,
        };
        const name = item.name;
        return obj;
      });
      console.log(newFsData, 'newFsData---')
      const resData: any = sortCpasTable(newFsData.slice(0));
      setReportResult(resData);
    } else {
      return message.error("数据加载失败");
    }
  };
  // 汇总数据

  // 重算  获取 汇总数据
  const rerunFun = async () => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    setPercentNum(0)
    // setIsClickRerun(true);
    await setInit()
  }
  const items: MenuProps['items'] = [
    {
      label: "追加到EXCEL底稿",
      key: '0',
    },
    {
      label: "输出到EXCEL文件",
      key: '1',
    },
  ];
  const handleChange = (value: string) => {
    if (value === "open"|| value==="") {
      setActiveKeyArr([])
      dataList.map((item: any) => {
        const id = item.id ? item.id : item.fid;
        activeKeyArr.push(id)
        setActiveKeyArr([...activeKeyArr])
      })
    } else if (value === "close") {
      setActiveKeyArr([])
    }
    console.log(`selected ${value}`);
  };
  const changeActiveKey = (id: any) => {
    setActiveKeyArr(id)
  }

  function groupNumbers(number, groupSize) {
    const groups = [];

    while (number > groupSize) {
      groups.push(groupSize);
      number -= groupSize;
    }

    if (number > 0) {
      groups.push(number);
    }

    return groups;
  }

  /**
   * 整页的计算方式
   */
  // const exportFun = async () => {
  //   setIsLoading(true);
  //   const el = treeRef.current;
  //   const rect = el.getBoundingClientRect();
  //   const pageWidth = 595.28;
  //   const max = 60000;
  //   const rectHeight = rect.height;
  //   const groupsNumber: number[] = groupNumbers(rectHeight,max);
  //   const canvas = [];
  //   let countStep = 0;
  //   for (let i = 0 ; i < groupsNumber.length ; i++) {
  //     const step = groupsNumber[i];
  //     const y = i === 0 ? 0 : countStep;
  //     const canvasElement = await html2canvas(el, { allowTaint: false,
  //       useCORS: true, scrollX:0, y:y, height:step });
  //     canvas.push(canvasElement)
  //     countStep += step;
  //   }
  //   try {
  //     //内容的总宽度
  //     const contentWidth = rect.width;
  //     //内容的总高度
  //     const contentHeight = rect.height;
  //
  //     //按照A4比例的总高度
  //     const pageHeight = (pageWidth / contentWidth) * contentHeight;
  //
  //     console.log(`********************** 要绘制pdf高度 :  pageHeight:${pageHeight} *******************************`)
  //
  //     //canvas转图片数据
  //     const PDF = new JsPDF({
  //       orientation:"p",
  //       unit:"pt",
  //       format:[pageWidth,100000]
  //     });
  //     console.log(`开始PDF绘制 :  groupsNumber:${groupsNumber}`)
  //     let position = 0;
  //     for (let i = 0 ; i<canvas.length;i++){
  //       //一页pdf显示htm1页面生成的canvas高度，a4纸的尺寸[595.28,841.89];
  //       const canvasElement = canvas[i];
  //       const imgHeight = (pageWidth / contentWidth) * canvasElement.height;
  //       console.log(`********************** 要绘制的canvas高度 :  imgHeight:${imgHeight} *******************************`)
  //       const pageData = canvasElement.toDataURL("img/jpeg", 1.0);
  //       PDF.addImage(pageData, "JPEG", 0, position, pageWidth, imgHeight);
  //       console.log(`********************** PDF  :   PDF.addImage(pageData, "JPEG", 0, position:${position}, pageWidth:${pageWidth}, imgHeight:${imgHeight});`)
  //       position -= imgHeight;
  //     }
  //     PDF.save("勾稽汇总" + ".pdf");
  //     setIsLoading(false);
  //   }catch (e) {
  //     throw e
  //   }finally {
  //     setIsLoading(false);
  //   }
  // }


  /**
   *  分页的计算方式
   */
  const exportFun = async () => {

      // TODO 分页的时候文字被截断
      // 如果想解决这个问题,需要在勾稽汇总界面在 visible：hidden 一个和现有汇总区域一样的界面. 只不过该区域采用平级结构,
      // 将分类头和每一条公式拍平成一个List
      // 修改分页的算法, 遍历每个 li 元素累加高度, 当大于 pageHeight 则将该元素分割到下一页面去.
      // 由于现在是父元素多层嵌套方式, 无法做到按照公式粒度进行分页.

      const el = treeRef.current;
      const rect = el.getBoundingClientRect();
      const pageWidth = 595.28;
      const pageHeight = 841.89;
      const max = pageHeight * 40;
      const rectHeight = rect.height;
      const groupsNumber: number[] = groupNumbers(rectHeight,max);
      const canvas = [];
      let countStep = 0;
      for (let i = 0 ; i < groupsNumber.length ; i++) {
        const step = groupsNumber[i];
        const y = i === 0 ? 0 : countStep;
        const canvasElement = await html2canvas(el, {
          allowTaint: false,
          scale: 1,
          useCORS: true, scrollX:0, y:y, height:step });
        canvas.push(canvasElement)
        countStep += step;
      }
      try {
        // document.querySelector("body")?.appendChild(canvas[0]);
        // document.querySelector("body")?.appendChild(canvas[1]);
        //内容的总宽度
        const contentWidth = rect.width;
        //内容的总高度
        const contentHeight = rect.height;
        //a4纸的尺寸[595.28,841.89],htm1页面生成的canvas在pdf中图片的宽高
        //canvas转图片数据
        const PDF = new JsPDF("","pt","a4");
        console.log(`开始PDF绘制 :  groupsNumber:${groupsNumber}`)
        for (let i = 0 ; i<canvas.length;i++){
          //页面偏移
          let position = 0;
          //一页pdf显示htm1页面生成的canvas高度，a4纸的尺寸[595.28,841.89];
          const canvasElement = canvas[i];
          const imgHeight = (pageWidth / contentWidth) * canvasElement.height;
          console.log(`********************** 要绘制的canvas高度 :  imgHeight:${imgHeight} *******************************`)
          let leftHeight = imgHeight;
          console.log(`leftHeight高度 :  leftHeight:${leftHeight}`)
          const pageData = canvasElement.toDataURL("img/jpeg", 1.0);
          if (leftHeight < pageHeight) {
            PDF.addImage(pageData, "JPEG", 0, position, pageWidth, imgHeight);
          } else {
            console.log(`检测到图像宽度大于pageHeight :  pageHeight:${pageHeight} 开始分页处理`)
            while (leftHeight > 0) {
              PDF.addImage(pageData, "JPEG", 0, position, pageWidth, imgHeight);
              console.log(`PDF.addImage : 0, position:${position}, pageWidth:${pageWidth}, imgHeight:${imgHeight} `)
              leftHeight -= pageHeight;
              console.log(`leftHeight -= pageHeight leftHeight = ${leftHeight}`)
              position -= pageHeight;
              console.log(`position -= pageHeight position:${position}`)
              if (leftHeight > 0) {
                console.log(`添加页面`)
                PDF.addPage();
              }
            }
            console.log(`**********************leftHeight<=0 leftHeight:${leftHeight} 结束本次canvas pdf绘制**************************`);
          }
        }

        PDF.save(`${title}.pdf`);
        setIsLoading(false);
      }catch (e) {
        throw e
      }finally {
        setIsLoading(false);
      }
  }
  const initReloadData = () => {
    // if (localStorage.getItem("dbNameData")) {
      const totalObj: any = localStorage.getItem(`${storageName}-${dbname}`)
      const newObj = totalObj ? JSON.parse(totalObj) : null;
      if (newObj && dbname === newObj.dbname) {
      setTotalData(newObj.ntotalData)
      setOtherData(newObj.otherInfo);
      if(storageName === "fsNameData") {
        const res = sortCpasTable(newObj.ndataList, "title");
        setDataList(res);
      }else {
        setDataList(newObj.ndataList);
      }
      const newList: any = []
      newObj.ndataList.map((item: any) => {
        const id = item.id ? item.id : item.fid;
        newList.push(id)
      })

      setActiveKeyArr(newList)
      // }
    } else {
      setDataList([])
    }
    // setTypeList(list)

  }
  const onChangeRulesType = (item: any) => {
    setSelectedItems(item)
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    reloadData()
  }
  const onChangeReportPro = (item: any) => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    reloadData()
  }
  const onChangeResult = (item: any) => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    reloadData()
  }
  //报表需要排序
  const getSortData =(data: any) => {
    // if(!data || !data.length) {
    //   return
    // }
    let sortList;
    if(type === "fs") {
      sortList = sortCpasTable(data, "title")
    }else {
      sortList = data
    }
    setDataList(sortList);
  }
  const notesTreeSort = (resetTargetData: any, oldDataList: any) => {
    if(!resetTargetData || !resetTargetData.length) {
      return;
    }
    const sourceTreeArr: any = oldDataList.slice();
    let sort_arr = new Array(oldDataList.length).fill(null);
    console.log(sourceTreeArr, "sourceTreeArr---");
    // 进行位置对比，将勾稽汇总的树。按照源树进行排序
    for (let i = 0; i<resetTargetData.length; i++){
      for (let j = 0; j<sourceTreeArr.length; j++){
        if (resetTargetData[i].id === sourceTreeArr[j].id){
          sort_arr[j] = resetTargetData[i];
        }
      }
    }
    //过滤掉无用Null占位
    sort_arr = sort_arr.filter((item)=>item!==null);
    return sort_arr;
  }
  const reloadData = () => {
    const totalObj: any = localStorage.getItem(`${storageName}-${dbname}`) || "{}"
    const list = JSON.parse(totalObj)
    const { ndataList } = list
    const typeItem = form.getFieldsValue().typeList
    let name = form.getFieldsValue().reportList
    const rules = form.getFieldsValue().resultList
    let currentDataList = ndataList && ndataList.length ? ndataList.slice() : [];
    if(type !=="fs" && notesChecks && notesChecks.length) {
      name = notesChecks.slice();
    }
    if(type !=="fs" && (!notesChecks || !notesChecks.length)) {
      name = [];
    }
    console.log(name, '披露项目名称', notesChecks);
    if(reportChecks && reportChecks.length) {
      const datas: any = [];
      for(let i =0;i <reportChecks.length;i ++) {
        ndataList.map((item: any) => {
          const currentData: any = reportResult.filter((r: any) => r.fid === item.fid); //匹配到数据
          if(currentData && currentData.length && currentData[0].associatedReport) {
            item.associatedReport = currentData[0].associatedReport;
          }
          if(item.associatedReport && item.associatedReport.includes(reportChecks[i])) {
            datas.push(item);
          }
        });
      }

      console.log([...new Set(datas)], '[...new Set(datas)]---');
      // currentDataList = [...new Set(datas)];
      currentDataList = notesTreeSort([...new Set(datas)], ndataList);
    }else {
      currentDataList = ndataList && ndataList.length ? ndataList.slice() : [];
    }
    console.log(currentDataList, 'currentDataList---');
    if(!currentDataList || !currentDataList.length) {
      setDataList([]);
      return;
    }
    if (typeItem.length > 0 && name.length === 0 && rules.length === 0) {
      const typeList: any = []
      currentDataList.map((item: any) => {
        item.verifyResult?.map((r: any) => {
          if (typeItem.includes(r.type)) {
            typeList.push(item)
          }
        })
      })
      console.log("执行type", [...new Set(typeList)]);
      getSortData([...new Set(typeList)]);
      // setDataList([...new Set(typeList)])
    }
    if (typeItem.length > 0 && name.length > 0 && rules.length === 0) {
      let datas: any = []
      currentDataList.map((item: any) => {
        item.verifyResult.map((r: any) => {
          if (typeItem.includes(r.type)) {
            datas.push(item)
          }
        })
      })
      datas = [...new Set(datas)]
      const dataLists = datas.filter((item: any) => name.includes(item.title))
      console.log("执行type name", dataLists);
      getSortData(dataLists);
      // setDataList(dataLists)
    }
    if ((typeItem.length > 0 && name.length > 0 && rules.length > 0) || (typeItem.length > 0 && name.length === 0 && rules.length > 0)) {
      let datas: any = []
      let relesList: any = []
      currentDataList.map((item: any) => {
        item.verifyResult.map((r: any) => {
          if (typeItem.includes(r.type)) {
            datas.push(item)
          }
        })
      })
      datas = [...new Set(datas)]
      const dataLists = name.length > 0 ?  datas.filter((item: any) => name.includes(item.title)) : datas;
      dataLists.map((item: any) => {
        const newVerifyResult: any = [];
        item.verifyResult.map((r: any) => {
          rules.map((i: any) => {
            const isRepeat = newVerifyResult.filter((s: any) => r.number === s.number);
            if (i === "1") {
              if (!r.fullFormulaResult && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "2") {
              if (!r.fullFormulaResult && r.isForce && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "3") {
              if (!r.fullFormulaResult && !r.isForce && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "4") {

              if (r.fullFormulaResultFormat === "2"  && !r.fullFormulaResult && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "5") {
              if (r.fullFormulaResultFormat === "1" && !r.fullFormulaResult && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
          })
        })
        if(newVerifyResult && newVerifyResult.length) {
          relesList.push({
            ...item,
            verifyResult: newVerifyResult
          })
        }
      })
      relesList = [...new Set(relesList)]
      console.log("执行type name rules", relesList);
      getSortData(relesList);
      // setDataList(relesList)
    }
    if (typeItem.length === 0 && name.length > 0 && rules.length === 0) {
      const datalist = currentDataList ? currentDataList.filter((item: any) => name.includes(item.title)) : null
      console.log("执行name", datalist);
      getSortData(datalist);
      // setDataList(datalist)
    }
    if (typeItem.length === 0 && name.length > 0 && rules.length > 0) {
      const datalist = currentDataList.filter((item: any) => name.includes(item.title))
      let nameAndRules: any = []
      datalist.map((item: any) => {
        const newVerifyResult: any = [];
        item.verifyResult.map((r: any) => {
          rules.map((i: any) => {
            const isRepeat = newVerifyResult.filter((s: any) => r.number === s.number);
            if (i === "1") {
              if (!r.fullFormulaResult && !isRepeat.length) {
                // nameAndRules.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "2") {
              if (!r.fullFormulaResult && r.isForce && !isRepeat.length) {
                // nameAndRules.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "3") {
              if (!r.fullFormulaResult && !r.isForce && !isRepeat.length) {
                // nameAndRules.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "4") {
              if (r.fullFormulaResultFormat === "2"  && !r.fullFormulaResult && !isRepeat.length) {
                // nameAndRules.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "5") {
              if (r.fullFormulaResultFormat === "1" && !r.fullFormulaResult && !isRepeat.length) {
                // nameAndRules.push(item)
                newVerifyResult.push(r);
              }
            }
          })
        })
        if(newVerifyResult && newVerifyResult.length) {
          nameAndRules.push({
            ...item,
            verifyResult: newVerifyResult
          })
        }
      })
      nameAndRules = [...new Set(nameAndRules)]
      console.log("执行name rules", nameAndRules);
      getSortData(nameAndRules);
      // setDataList(nameAndRules)
    }
    if (typeItem.length === 0 && name.length === 0 && rules.length > 0) {
      console.log(rules, 'rules----');
      let relesList: any = []
      currentDataList.map((item: any) => {
        const newVerifyResult: any = [];
        item.verifyResult.map((r: any) => {
          rules.map((i: any) => {
            const isRepeat = newVerifyResult.filter((s: any) => r.number === s.number);
            if (i === "1") {
              if (!r.fullFormulaResult && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "2") {
              if (!r.fullFormulaResult && r.isForce  && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "3") {
              if (!r.fullFormulaResult && !r.isForce  && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "4") {
              if (r.fullFormulaResultFormat === "2" && !r.fullFormulaResult  && !isRepeat.length) {
                console.log(r, 'r----');
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
            if (i === "5") {
              if (r.fullFormulaResultFormat === "1" && !r.fullFormulaResult  && !isRepeat.length) {
                // relesList.push(item)
                newVerifyResult.push(r);
              }
            }
          })
        })
        if(newVerifyResult && newVerifyResult.length) {
          relesList.push({
            ...item,
            verifyResult: newVerifyResult
          })
        }
      })
      relesList = [...new Set(relesList)]
      console.log("执行relus", relesList);
      getSortData(relesList);
      // setDataList(relesList)
    }
    if (typeItem.length === 0 && name.length === 0 && rules.length === 0) {
      getSortData(currentDataList);
      // setDataList(ndataList)
    }
  }
  const judgements = (item: any[], list: any[]) => {
    const res: any = []
    const result: any = []
    item.map((i: any) => {
      if (i === "1") {
        list.map((a: any) => {
          a.verifyResult?.map((f: any) => {
            if (!f.fullFormulaResult) {
              result.push(f)
              a.verifyResult = [...new Set(result)]
              res.push(a)
            }
          })
        })
      }
      if (i === "2") {
        list.map((a: any) => {
          a.verifyResult?.map((f: any) => {
            if (!f.fullFormulaResult && f.isForce) {
              result.push(f)
              a.verifyResult = [...new Set(result)]
              res.push(a)
            }
          })
        })
      }
      if (i === "3") {
        list.map((a: any) => {
          a.verifyResult?.map((f: any) => {
            if (!f.fullFormulaResult && !f.isForce) {
              result.push(f)
              a.verifyResult = [...new Set(result)]
              res.push(a)
            }
          })
        })
      }
      if (i === "4") {
        list.map((a: any) => {
          a.verifyResult?.map((f: any) => {
            if (f.fullFormulaResultFormat === "2") {
              result.push(f)
              a.verifyResult = [...new Set(result)]
              res.push(a)
            }
          })
        })
      }
      if (i === "5") {
        list.map((a: any) => {
          a.verifyResult?.map((f: any) => {
            if (f.fullFormulaResultFormat === "1") {
              result.push(f)
              a.verifyResult = [...new Set(result)]
              res.push(a)
            }
          })
        })
      }
    })
    const newRes = [...new Set(res)]
    setDataList(newRes)
  }
  const formulaResult = (t: any) => {
    // const results = t.verifyFormulaResult?.toFixed(2)-t.beVerifiedFormulaResult?.toFixed(2)
    // return formatPrice(results.toFixed(2))
    const fixedNum =
      t.verifyFormulaResult.toFixed(2) -
      t.beVerifiedFormulaResult.toFixed(2);
    const sourceNum = t.verifyFormulaResult - t.beVerifiedFormulaResult;
    if (fixedNum === 0 && sourceNum < 0.01 && (fixedNum !== sourceNum)) {
      return Number(sourceNum.toFixed(4));
    }
    return formatPrice(fixedNum.toFixed(2));
  }
  const displayNum = (item, type) => {
    const fixedNum =
      item.verifyFormulaResult.toFixed(2) -
      item.beVerifiedFormulaResult.toFixed(2);
    const sourceNum = item.verifyFormulaResult - item.beVerifiedFormulaResult;
    const value =
      type === "verify"
        ? item.verifyFormulaResult
        : item.beVerifiedFormulaResult;
    if (fixedNum === 0 && sourceNum < 0.01 && (fixedNum !== sourceNum)) {
      return Number(value);
    }
    return formatPrice(value.toFixed(2));
  };
  const formulaList = (t: any) => {
    if (t.fullFormulaResultFormat === "1") {
      return (
        <span style={!t.fullFormulaResult ? { color: "#f50"} : {}}>
          {!t.fullFormulaResult ? "逻辑不符" : "校验通过"}
        </span>
      )
    }
    // else if (t.fullFormulaResultFormat === "2") {
    //   return (
    //     <span style={{ color: "#f50", }}>
    //       差异：{formulaResult(t)}
    //       <span style={{ marginLeft: "30px" }}>
    //         {displayNum(t, "beVerify")}
    //         {t.operation}
    //         {displayNum(t, "verify")}
    //       </span>
    //     </span>
    //   )
    // }
    else {
      return (
        <span style={!t.fullFormulaResult ? { color: "#f50"} : {}}>
          {/* 差异：{formatPrice(t.verifyFormulaResult.toFixed(2)-t.beVerifiedFormulaResult?.toFixed(2))} */}
          差异：{formulaResult(t)}
          <span style={{ marginLeft: "30px" }}>
            {displayNum(t, "beVerify")}
            {t.operation}
            {displayNum(t, "verify")}
          </span>
        </span>
      )
    }
  }

  /**
   * 平级结构转数树结构
   * @param score
   * @param pid
   */
  function convertLevelToTree(score: any, pid = null) {
    const tree: any = [];
    score.map((item: any)=>{
      if(item.pid === pid) {
        // 递归寻找
        item.children = convertLevelToTree(score, item.id);
        tree.push(item);
      }
    });
    return tree;
  }

  /**
   * 按照深度递归的顺序，平铺节点
   */
  const deepTree = (data: any, arr: any[] = []) => {
    for (let i = 0; i < data.length; i++) {
      const item: any = data[i]
      const clone_item = _.cloneDeep(item);
      delete clone_item.children;
      arr.push(clone_item)
      if (item.children && item.children.length) {
        deepTree(item.children, arr)
      }
    }
    return arr
  }

  /**
   * 重新排序一下树节点,按照深度递归的顺序，平铺节点
   */
  async function sortTreeByChildren(data: any) {
    // 从库里查出来的数据会保证同级下的顺序数组，order by pid,orderNumber.
    // 所以直接转成树形结构会保证同级下的顺序
    // 由于数据库里没有存储level层级，所以需要先转成树形结构，再按照深度递归的方式转成平铺的数组
    const dataId = await getDataId()
    // 获取原树
    const resData = await getLeftTreeList(dbname, dataId);
    const sourceTreeArr: any = [];
    // 按照深度递归平铺原树
    deepTree(convertLevelToTree(resData),sourceTreeArr);
    // 检测无父ID的提升 , 勾稽汇总的树
    const resetTargetData =  resetPidIfNotFound(data);
    // 按照原树进行填充位置
    let sort_arr = new Array(sourceTreeArr.length).fill(null);
       // 进行位置对比，将勾稽汇总的树。按照源树进行排序
       for (let i = 0; i<resetTargetData.length; i++){
         for (let j = 0; j<sourceTreeArr.length; j++){
           if (resetTargetData[i].id === sourceTreeArr[j].id){
             sort_arr[j] = resetTargetData[i];
           }
         }
       }
      //过滤掉无用Null占位
      sort_arr = sort_arr.filter((item)=>item!==null);
      return sort_arr;
  }
  const getDataStateHandle = () => {
    let total = 0
    const timer = setInterval(async ()=> {
      if (total < 100) {
        const res = await queryDataState({ type: "verify" })
        console.log(res);
        total = parseInt(res.data.process)
        setPercentNum(total)
        setContentMsg(res.data.message)
        console.log(total, 'total--------');
        if (res.ok && total === 100) {
          await queryResetState({process: 0,type: "verify"})
          clearInterval(timer)
          console.log("clearInterval")
        }
      }
    }, 100)
  };
  const setInit = async () => {
    setShowOpen(true)
    await getDataStateHandle();
    const dateId = await getDataId()
    const params = {
      dbname,
      data_id: dateId,
    }
    if(type === "fs") {
      params.cpasTableType = type;
    }
    const res: any = await getAllData(params)
    if (res.ok) {
      await Dexie.delete("cpasCacheDb")
      const { data } = res
      if(!data || data && JSON.stringify(data) === "[]") {
        setShowOpen(false)
        return message.success("重算成功！")
      }
      const { verifySummaryItemList, statistics, time, version, appVersion } = data;
      let sortVerifySummaryItemList: any = [];
      if(type !== "fs") {
        sortVerifySummaryItemList = await sortTreeByChildren(verifySummaryItemList);
        console.log(sortVerifySummaryItemList, 'sortVerifySummaryItemList 处理数据展示');
      }
      const dbNameData = {
        dbname,
        ntotalData: statistics,
        ndataList: type === "fs" ? verifySummaryItemList : sortVerifySummaryItemList,
        otherInfo: {
          time,
          version,
          appVersion
        }
      }
      localStorage.setItem(`${storageName}-${dbname}`, JSON.stringify(dbNameData))
      setTotalData(statistics)
      setOtherData({
        time,
        version,
        appVersion
      });
      setDataList(verifySummaryItemList)
      setShowOpen(false)
      await initReloadData()
      await reloadData()
      if(modileIsReturn) {
        modileIsReturn(true);
      }
      return message.success("重算成功！")
    } else {
      setShowOpen(false)
      return message.error(res.msg)
    }
  }
  const genExtra = (item: any) => (
    <div
      onClick={(event) => {
        // If you don't want click extra trigger collapse, you can prevent this:
        console.log("genExtra-item", item);
        if(type === "ds") {
          openVerifyDetail({
            ...item,
          }, true);
        }else {
          openVerifyDetail({
            ...item,
          });
        }
        event.stopPropagation();
        return false
      }}>
      详情
      <DoubleRightOutlined />
    </div>
  );

  function renderInfo(key: any, index: any , groupVerifyResult: any){
      return (
        <li key={key} className="rules-list">
          <p>{index + 1}、{RulesType[key]}</p>
          {
            groupVerifyResult.map((f: any) => {
              if(f?.dynamicType !== "MAIN") {
                return (
                  <>
                    <p>
                      勾稽关系{f.number} ：{
                      f.isForce ?
                        <div style={{width:55,height:22,backgroundColor:"#f50",display:"inline-block",textAlign:"center",color:"white",marginRight:5}}>强制</div> :
                        <div  style={{width:55,height:22,backgroundColor:"#87d068",display:"inline-block",textAlign:"center",color:"white",marginRight:5}}>非强制</div>
                    }
                      {formulaList(f)}
                    </p>
                    <p>{f.fullFormula}</p>
                  </>
                )
              }
            })
          }
        </li>
      )
  }

  function renderList(){
    if(!dataList || !dataList.length) {
      return;
    }
    const cloneData = _.cloneDeep(dataList);
    const groupDataByType = cloneData.map((item: any)=>{
      item.verifyResult = _.groupBy(item.verifyResult, 'type');
        return item;
    })
    return (
      groupDataByType.length > 0
        ?
        <Collapse activeKey={activeKeyArr} onChange={changeActiveKey}>
          {
            groupDataByType.map((item: any) => {
              const verifyResult = item.verifyResult;
              let mainLen = 0;
              //@临时方案，总数需要减去母公式的数据
              if(verifyResult) {
                Object.keys(verifyResult).map((key, index) => {
                  const mainVerifyResult = item.verifyResult[key] ? item.verifyResult[key].filter((r: any) => r.dynamicType && r.dynamicType === "MAIN") : null;
                  if(mainVerifyResult && mainVerifyResult.length) {
                    mainLen = mainLen+mainVerifyResult.length;
                  }
                });
              }
              /*兼容处理公式没有匹配上的情况 begin*/
              const verifyKeys = Object.keys(item.verifyResult);
              // let isCludesKey = true; //默认可以匹配上
              if(selectedItems && selectedItems.length && verifyKeys) {
                for(let i =0;i <selectedItems.length; i++) {
                  if(!verifyKeys.includes(selectedItems[i])) {
                    return
                  }
                }
              }
              /*兼容处理公式没有匹配上的情况 end*/
              const total = mainLen ? parseInt(item.statisticsItem.total)- mainLen : item.statisticsItem.total;
              return <Panel header={`${item.title}   共${total}条，校验不通过${item.statisticsItem.fail}条`} key={item.id || item.fid}   extra= {genExtra(item)}>
                {
                  item.verifyResult
                    ?
                    <ul>
                      {
                        Object.keys(item.verifyResult).sort().map((key: any, index: any) => {
                              const groupVerifyResult = sortValidtorData(item.verifyResult[key]);
                              if(selectedItems.length > 0 && selectedItems.includes(key)) {
                                return renderInfo(key, index, groupVerifyResult);
                             }else if(selectedItems.length === 0){
                                return renderInfo(key, index, groupVerifyResult);
                             }else{
                                return null
                             }
                        })
                      }
                    </ul>
                    :
                    <div className="no-rules">暂未设置勾稽校验</div>
                }
              </Panel>
            })
          }
        </Collapse>
        :
        <div className="no-data">暂无数据</div>
    )
  }
  const reportClick = (e: any) => {
    console.log("input click");
    setReportModalOpen(true)
  }
  const reportClear = () => {
    setReportInputValue("");
    setReportChecks([]);
    reportTreeView?.current?.instance.unselectAll();
  }

  const treeViewSelectionChanged = (e: any) => {
    console.log("selection change");
    const treeView = e.component;
    const syncSelectedEmployees = treeView.getSelectedNodes()
      .map((node: any) => node.itemData.key);
    setReportChecks([...syncSelectedEmployees]);
  }

  const notesTreeViewSelectionChanged = (e: any) => {
    console.log("selection change");
    const treeView = e.component;
    const syncSelectedEmployees = treeView.getSelectedNodes()
      .map((node: any) => node.itemData.key);
    setNotesChecks([...syncSelectedEmployees]);
  }
  const renderTreeViewItem = (item: { title: any; position: any; }) => `${item.title}`;
  const renderReport = () => {
    if(type === "fs") {
      return;
    }
    return (
      <Form.Item label="报表项目" name="reportProject">
        {/* <Input onClick={reportClick} className="report-project" value={reportInputValue} addonAfter={<CloseOutlined onClick={reportClear}/>}/> */}
        <Input onClick={reportClick} className="report-project" value={ellipsis(reportInputValue, 7)} placeholder="请选择报表项目" style={{width: 120}}/>
        <span style={{display: "none"}}>{reportInputValue}</span>
      </Form.Item>
    );
  }
  const notesClick = () => {
    console.log("input click");
    setNotesModalOpen(true)
  };
  const renderSelectList =() => {
    if(type !== "fs") {
      return (
        <Form.Item label="披露项目" name="reportList">
          {/* <Input onClick={reportClick} className="report-project" value={reportInputValue} addonAfter={<CloseOutlined onClick={reportClear}/>}/> */}
          <Input onClick={notesClick} className="report-project" value={ellipsis(notesInputValue, 7)} placeholder="请选择披露项目" style={{width: 120}}/>
          <span style={{display: "none"}}>{notesInputValue}</span>
        </Form.Item>
      )
    }
    return (
      <Form.Item label={type === "fs" ?  "报表项目" : "披露项目"} name="reportList">
        <Select
          allowClear
          showSearch
          mode="multiple"
          placeholder={type === "fs" ?  "请选择报表项目" : "请选择披露项目"}
          value={reportItem}
          style={{ minWidth: '120px', }}
          onChange={onChangeReportPro}
          maxTagCount={1}
          maxTagTextLength={3}
          options={filteredReportOpation.map((item: any) => ({
            value: item.title,
            label: item.title,
          }))}
        />
      </Form.Item>
    )
  }
  //计算所有母公式的数据
  function calculateAllMain() {
    let mainLen = 0;
    if(!dataList || !dataList.length) {
      return mainLen;
    }
    const cloneData = _.cloneDeep(dataList);
    const groupDataByType = cloneData.map((item: any)=>{
      item.verifyResult = _.groupBy(item.verifyResult, 'type');
        return item;
    })
    if(!groupDataByType || !groupDataByType.length) {
      return mainLen
    }
    groupDataByType.map((item: any) => {
      const verifyResult = item.verifyResult;
      //@临时方案，总数需要减去母公式的数据
      if(verifyResult) {
        Object.keys(verifyResult).map((key, index) => {
          const mainVerifyResult = item.verifyResult[key] ? item.verifyResult[key].filter((r: any) => r.dynamicType && r.dynamicType === "MAIN") : null;
          if(mainVerifyResult && mainVerifyResult.length) {
            mainLen = mainLen+mainVerifyResult.length;
          }
        });
      }
    })
    return mainLen;
  }
  useEffect(() => {
    if(type === "fs") {
      initFsTableData();
    }else {
      // getReportProject();
      getReportList();
    }
    initReloadData()
  },[])

  useEffect(() => {
    if(type !== "fs") {
      getReportProject();
    }
  }, [isReportModalOpen]);

  useEffect(() => {
    reloadData();
  }, [reportInputValue, notesInputValue]);
  const allMainLen = calculateAllMain();
  const allTotal = allMainLen ? parseInt(totalData?.total)-allMainLen : totalData?.total; //兼容后端，减掉母公式数据。@todo后续配合后端需要还原
  return (
    <>
      <PageLoading
        isOpen={isLoading}
        isMaskClose={false}
        className="art-page-loading"
        // content={"勾稽汇总pdf生成中..."}
        width={200}
      />
      <div className="summary">

        <h1 className="title">{title}</h1>
        <div className="form">
          <Row>
            <Col span={20}>
              <Form layout="inline" form={form}
                    initialValues={
                      {
                        typeList: [],
                        reportList: [],
                        resultList: [],
                        isShow: "open"
                      }
                    }
              >
                <Form.Item label="校验类型" name="typeList">
                  <Select
                    allowClear
                    mode="multiple"
                    placeholder="请选择校验类型"
                    value={selectedItems}
                    style={{ minWidth: '120px' }}
                    onChange={(e: any) => onChangeRulesType(e)}
                    options={storageName === "fsNameData" ? OPTIONS.slice(0, OPTIONS.length-1) : OPTIONS}
                    maxTagCount={2}
                    maxTagTextLength={3}
                  />
                </Form.Item>
                {renderSelectList()}
                {renderReport()}
                <Form.Item label="校验结果" name="resultList">
                  <Select
                    // showSearch
                    allowClear
                    mode="multiple"
                    placeholder="请选择校验结果"
                    value={resultItems}
                    style={{ minWidth: '120px'}}
                    onChange={onChangeResult}
                    maxTagCount={2}
                    maxTagTextLength={3}
                    options={RESULT_OPATIONS}
                  />
                </Form.Item>
                <Form.Item label="全部分组" name="isShow">
                  <Select
                    allowClear
                    placeholder="请选择"
                    style={{ maxWidth: '100px' }}
                    onChange={handleChange}
                    options={[
                      {
                        value: 'open',
                        label: '展开',
                      },
                      {
                        value: 'close',
                        label: '收起',
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
            </Col>
            <Col span={2}>
              <Button size="small" type="primary" onClick={rerunFun}>重算</Button>
            </Col>
            <Col span={2}>
              <Button size="small" type="primary" onClick={()=>{
                setIsLoading(true);
                setTimeout(async ()=>{
                  await exportFun()
                },300)
              }}>导出</Button>
              {/* <Dropdown menu={{ items }} trigger={['click']}>
              <a onClick={e => e.preventDefault()}>
                <Button size="small" type="primary" onClick={exportFun}>导出</Button>
              </a>
            </Dropdown> */}
            </Col>
          </Row>
        </div>
        {/* <div className="total-all">
        <Row>
          统计：共{totalData?.total||0}条,
          校验不通过{totalData?.fail||0}条，
          其中强制校验不通过{totalData?.force_fail||0}条，
          非强制校验不通过{totalData?.not_force_fail||0}条。
        </Row>
      </div> */}
        <div className={'content-all-box'}>
            <div className="content-all">
                <div  ref={treeRef}>
                  <div className="total-all">
                    <div>
                      统计：共{totalData?.total || 0}条,
                      校验不通过{totalData?.fail||0}条，
                      其中强制校验不通过{totalData?.force_fail||0}条，
                      非强制校验不通过{totalData?.not_force_fail || 0}条。
                    </div>
                    <div>{otherData?.time ? `上次执行重算时间：${otherData?.time}` : ""}</div>
                  </div>
                  {
                    renderList()
                  }
              </div>
            </div>
        </div>
        <Modal
          title="报表项目"
          open={isReportModalOpen}
          destroyOnClose={true}
          maskClosable={false}
          cancelText="清空条件"
          closable={false}
          onCancel={async () => {
            if(reportTreeView) {
              reportTreeView?.current?.instance.unselectAll();
            }
            setReportChecks([]);
            setReportInputValue("");
            setReportModalOpen(false);
            // reloadData();
          }}
          onOk={() => {
            setReportInputValue(reportChecks.join(","));
            setReportModalOpen(false);
            reloadData();
          }}
        >
          <div style={{ height: "50vh", overflow: "auto" }}>
            {/* <TextBox
              showClearButton={true}
              mode={"search"}
              value={searchValue}
              onValueChanged={(e) => onSearchValueChanged(e)}
            /> */}

          <TreeView
            id="treeviewReportProject"
            showCheckBoxesMode="normal"
            expandedExpr="expanded"
            selectNodesRecursive={false}
            searchEnabled={true}
            ref={reportTreeView}
            // dataStructure="plain"
            // ref={leftTreeRef}
            // parentIdExpr={"parentId"}
            // dataSource={getTreesData}
            // onItemClick={selectItem}
            selectionMode={"multiple"}
            selectByClick={treeViewSelectionChanged}
            onSelectionChanged={treeViewSelectionChanged}
            // onItemSelectionChanged={onItemSelectionChanged}
            displayExpr="title"
            itemRender={renderTreeViewItem}
            items={reportDataSource}
            virtualModeEnabled={true}
          />
            {/* <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onSearchChange} />
            <Tree
              checkable
              onCheck={(keys: any) => {
                setReportChecks(keys.checked)
              }}
              disabled={otherCheck}
              checkedKeys={reportChecks}
              treeData={reportDataSource}
              checkStrictly={true}
            /> */}
          </div>
        </Modal>
        <Modal
          title="披露项目"
          open={isNotesModalOpen}
          destroyOnClose={true}
          maskClosable={false}
          cancelText="清空条件"
          closable={false}
          onCancel={async () => {
            if(notesTreeView) {
              notesTreeView?.current?.instance.unselectAll();
            }
            setNotesChecks([]);
            setNotesInputValue("");
            setNotesModalOpen(false);
            // reloadData();
          }}
          onOk={() => {
            setNotesInputValue(notesChecks.join(","));
            setNotesModalOpen(false);
            reloadData();
          }}
        >
          <div style={{ height: "50vh", overflow: "auto" }}>
          <TreeView
            id="treeviewNotes"
            showCheckBoxesMode="normal"
            expandedExpr="expanded"
            selectNodesRecursive={false}
            searchEnabled={true}
            ref={notesTreeView}
            dataStructure="plain"
            // ref={leftTreeRef}
            parentIdExpr={"parentId"}
            // dataSource={reportResult}
            // onItemClick={selectItem}
            selectionMode={"multiple"}
            selectByClick={notesTreeViewSelectionChanged}
            onSelectionChanged={notesTreeViewSelectionChanged}
            displayExpr="title"
            keyExpr={"id"}
            // onItemSelectionChanged={onItemSelectionChanged}
            itemRender={renderTreeViewItem}
            items={reportResult}
            virtualModeEnabled={true}
          />
            {/* <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onSearchChange} />
            <Tree
              checkable
              onCheck={(keys: any) => {
                setReportChecks(keys.checked)
              }}
              disabled={otherCheck}
              checkedKeys={reportChecks}
              treeData={reportDataSource}
              checkStrictly={true}
            /> */}
          </div>
        </Modal>
        <Modal
          open={isShowOpen}
          footer={null}
          centered
          maskClosable={false}
          closable={false}
          title={null}
          bodyStyle={{background:"none"}}
          // style={{ height: "200px" }}
          className="dot-body"
          wrapClassName="spin-example"
        >
          <Progress percent={percentNum}  status="active" style={{color:"#fff"}}/>
          <div className="process-content">
            { contentMsg}
          </div>
        </Modal>
      </div>
    </>
  )
}
export default TabPageTwo
